import React from 'react';
import Spreadsheet from "x-data-spreadsheet";
import zhCN from 'x-data-spreadsheet/dist/locale/zh-cn';
import { connect } from 'dva';
import ResizeObserver from 'rc-resize-observer';
import { Button, message } from 'antd';

const options = {
    showToolbar: true,
    showGrid: true,
    showContextmenu: true,
    view: {
        height: () => window.innerHeight - 128,
        width: () => window.innerWidth - document.querySelector('.ant-layout-sider-children').clientWidth,
    },
    row: {
        len: 100,
        height: 25,
    },
    col: {
        len: 26,
        width: 100,
        indexWidth: 60,
        minWidth: 60,
    },
    style: {
        bgcolor: '#ffffff',
        align: 'left',
        valign: 'middle',
        textwrap: false,
        strike: false,
        underline: false,
        color: '#0a0a0a',
        font: {
            name: 'Helvetica',
            size: 10,
            bold: false,
            italic: false,
        },
    },
};

@connect(({ spreadsheet, loading }) => ({
    spreadsheet,
    loading: loading.models.spreadsheet,
}))
class SpreadsheetPage extends React.Component {
    constructor(props) {
        super(props);
        this.state = { loaded: false, dirty: false };
    }

    componentDidMount() {
        Spreadsheet.locale('zh-cn', zhCN);
        this.sheet = new Spreadsheet(this.refs.root, options)
            .change(data => {
                this.setState({ dirty: true });
            });

        // get spec
        // const json = JSON.stringify(this.sheet.getData())

        // set spec
        // this.sheet.loadData(JSON.parse(json))

        const { dispatch } = this.props;
        dispatch({
            type: 'spreadsheet/fetch',
            payload: {},
        });
    }

    shouldComponentUpdate(nextProps, nextState) {
        const oldJson = this.props.spreadsheet.json;
        const newJson = nextProps.spreadsheet.json;

        const { loaded } = nextState;

        try {
            if ( !loaded || newJson != oldJson) {
                this.sheet.loadData(JSON.parse(newJson));
                this.setState({ loaded: true, dirty: false });
            }
        } catch (error) {
            console.error(error);
        }

        // 我们自己处理后，就不用麻烦 react render 了
        // 但是在我们在 render 中使用 dirty 状态之后，又需要 render 了
        return true;
    }

    componentWillUnmount() {
        this.sheet && delete this.sheet;
    }

    reset() {
        this.sheet.sheet.editor.clear();

        const { spreadsheet: { json } } = this.props;
        this.sheet.loadData(JSON.parse(json));

        this.setState({ dirty: false });

        message.warning('表格内容已重置。');
    }

    save() {
        this.sheet.sheet.editor.clear();

        const { dispatch } = this.props;
        const json = JSON.stringify(this.sheet.getData());
        const callback = () => {
                message.success('表格内容已保存。');
        };
        dispatch({
            type: 'spreadsheet/update',
            payload: { json, callback },
        });

        // 重置状态
        this.setState({ dirty: false });
    }

    resize() {
        this.sheet.sheet.reload();
    }

    render() {
        const { dirty } = this.state;
        return (
            <>
                <div ref="root"></div>
                <div style={{ padding: '16px', backgroundColor: 'white', }}>
                    <Button type="primary" onClick={this.save.bind(this)} disabled={!dirty}>保存</Button> &nbsp;&nbsp;
                    <Button type="danger" onClick={this.reset.bind(this)} disabled={!dirty}>重置</Button>
                </div>
                <ResizeObserver onResize={this.resize.bind(this)}><div /></ResizeObserver>
            </>
        );
    }
}

export default SpreadsheetPage;
